//
//  WordsCollectionViewController.swift
//  ShimaPlayer
//
//  Created by michael on 2025/7/17.
//

import UIKit

class WordsCollectionViewController: UIViewController {

    private lazy var totalLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hexString: "#FFFFFF")
        label.font = .systemFont(ofSize: 12, weight: .bold)
        return label
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    func setupUI() {
        view.backgroundColor = UIColor(hexString: "#F5F5F5")

        let bgImage = UIImage.gradientImage(colors: [UIColor(hexString: "#15CC9D"), UIColor(hexString: "#52B9FB")],
                                            size: CGSizeMake(Size.screenWidth - 32, 71),
                                            startPoint: CGPoint(x: 0.25, y: 0.5),
                                            endPoint: CGPoint(x: 0.75, y: 0.5),
                                            locations: [0.18, 0.98],
                                            transform: CATransform3DMakeAffineTransform(CGAffineTransform(a: 0.85, b: 3.47, c: -0.15, d: 0.85, tx: 0.25, ty: -1.18))
        )
        let summaryCard = UIImageView(image: bgImage)
        summaryCard.layer.cornerRadius = 10
        summaryCard.layer.masksToBounds = true

        let totalTitleLabel = UILabel()
        totalTitleLabel.textColor = UIColor(hexString: "#FFFFFF")
        totalTitleLabel.font = .systemFont(ofSize: 17, weight: .bold)
        totalTitleLabel.text = "全部单词收藏"
        summaryCard.addSubview(totalTitleLabel)
        totalTitleLabel.snp.makeConstraints { make in
            make.top.leading.equalToSuperview().offset(12)
        }
        
        totalLabel.text = "1000"
        summaryCard.addSubview(totalLabel)
        totalLabel.snp.makeConstraints { make in
            make.leading.equalTo(totalTitleLabel).offset(4)
            make.bottom.equalToSuperview().inset(12)
        }

        let beginMemoryButton = UIButton(type: .system)
        beginMemoryButton.backgroundColor = UIColor(hexString: "#FFFFFF")
        beginMemoryButton.layer.cornerRadius = 14
        beginMemoryButton.setTitle("开始背词", for: .normal)
        beginMemoryButton.setTitleColor(UIColor(hexString: "#15CC9D"), for: .normal)
        beginMemoryButton.titleLabel?.font = .systemFont(ofSize: 13, weight: .medium)
        beginMemoryButton.addTarget(self, action: #selector(beginMemoryButtonTapped), for: .touchUpInside)
        summaryCard.addSubview(beginMemoryButton)
        beginMemoryButton.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.trailing.equalToSuperview().inset(12)
            make.height.equalTo(28)
            make.width.equalTo(76)
        }
        
        let createCard = UIView()
        createCard.backgroundColor = UIColor(hexString: "#FFFFFF")
        createCard.layer.cornerRadius = 10
        createCard.layer.masksToBounds = true
        let icon = UIImageView(image: UIImage(named: "btn_icon_add_gray"))
        let createLabel = UILabel()
        createLabel.textColor = UIColor(hexString: "#CCCCCC")
        createLabel.font = .systemFont(ofSize: 17, weight: .medium)
        createLabel.text = "创建单词收藏夹"
        let stackView = UIStackView(arrangedSubviews: [icon, createLabel])
        stackView.axis = .horizontal
        stackView.spacing = 10
        stackView.alignment = .center
        stackView.distribution = .equalSpacing
        createCard.addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }

        let tap = UITapGestureRecognizer(target: self, action: #selector(createCardTapped))
        createCard.addGestureRecognizer(tap)
        
        let items = [
            CollectionItemModel(title: "全部单词收藏", count: 1000, status: 0),
            CollectionItemModel(title: "全部单词收藏", count: 1000, status: 0),
            CollectionItemModel(title: "全部单词收藏", count: 1000, status: 0),
        ]

        summaryCard.frame = CGRect(x: 0, y: 0, width: Size.screenWidth - 32, height: 71)
        createCard.frame = CGRect(x: 0, y: 0, width: Size.screenWidth - 32, height: 48)
        
        let tableView = TableView<CollectionItemModel, CollectionItemModel, SwipeableCell<CollectionItemCell>>(style: .grouped)
            .backgroundColor(view.backgroundColor)
            .rowHeight(52)
            .spacing(insets: UIEdgeInsets(top: 12, left: 16, bottom: 12, right: 16), between: 12)
            .separatorStyle(.none)
            .tableViewHeader(summaryCard)
            .tableViewFooter(createCard)
            .sections(items)
            .rowsForSection { section in [items[section]] }
            .configureCell { cell, item, indexPath in
                cell.configure(with: item)
                cell.cornerRadius(10)
                cell.actionsContainerViewBackgroundColor(.red)
                cell.addAction(title: "删除", backgroundColor: .red, fontSize: 13, buttonWidth: 50) {
                        // Handle delete action
//                        self.items.remove(at: indexPath.row)
//                        tableView.deleteRows(at: [indexPath], with: .automatic)
                    }
            }

        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.verticalEdges.equalToSuperview()
            make.horizontalEdges.equalToSuperview().inset(12)
        }

    }

    @objc private func beginMemoryButtonTapped() {
        
    }
    
    @objc private func createCardTapped() {
        let bottomSheet = CreateCollectionBottomSheet()
        let popup = PopupView(contentView: bottomSheet, style: .bottomSheet(height: 140))
        popup.show(in: self)
        bottomSheet.onFinishButtonTapped = { title in
            print("title: \(title ?? "")")
            popup.dismiss()
        }
    }
    

}

class CreateCollectionBottomSheet: UIView {
    var onFinishButtonTapped: ((String?) -> Void)?

    private let titleTextField: UITextField = {
        let textField = UITextField()
        textField.borderStyle = .none
        textField.layer.masksToBounds = true
        textField.placeholder = "为你的收藏夹创建一个标题"
        textField.textAlignment = .right
        return textField
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        backgroundColor = UIColor(hexString: "FFFFFF")
        layer.cornerRadius = 25
        
        let indicatorView = UIView()
        indicatorView.backgroundColor = UIColor(hexString: "#C9CEDA")
        indicatorView.layer.cornerRadius = 1.5

        addSubview(indicatorView)
        indicatorView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(9)
            make.centerX.equalToSuperview()
            make.height.equalTo(3)
            make.width.equalTo(26)
        }
        
        let titleLabel = UILabel()
        titleLabel.text = "新建收藏夹"
        titleLabel.textColor = UIColor(hexString: "#1C1F1E")
        titleLabel.font = .systemFont(ofSize: 17, weight: .bold)
        titleLabel.textAlignment = .center
        
        addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(indicatorView.snp.bottom).offset(6)
            make.centerX.equalToSuperview()
        }

        let finishButton = UIButton(type: .system)
        finishButton.setTitle("完成", for: .normal)
        finishButton.setTitleColor(UIColor(hexString: "#CCCCCC"), for: .normal)
        finishButton.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)
        finishButton.addTarget(self, action: #selector(finishButtonTapped), for: .touchUpInside)
        
        addSubview(finishButton)
        finishButton.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(20)
            make.trailing.equalToSuperview().inset(16)
        }

        let bgView = UIView()
        bgView.backgroundColor = UIColor(hexString: "#FFFFFF")
        bgView.layer.cornerRadius = 10
        bgView.layer.shadowColor = UIColor(hexString: "#000000")?.withAlphaComponent(0.1).cgColor
        bgView.layer.shadowOpacity = 1
        bgView.layer.shadowOffset = CGSize(width: 0, height: 0)
        bgView.layer.shadowRadius = 4
        
        addSubview(bgView)
        bgView.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(23)
            make.horizontalEdges.equalToSuperview().inset(16)
            make.bottom.equalToSuperview().inset(33)
            make.height.equalTo(42)
        }

        let titleTitleLabel = UILabel()
        titleTitleLabel.textColor = UIColor(hexString: "#000000")
        titleTitleLabel.font = .systemFont(ofSize: 14, weight: .medium)
        titleTitleLabel.text = "标题"
        bgView.addSubview(titleTitleLabel)
        titleTitleLabel.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(10)
            make.centerY.equalToSuperview()
        }

        bgView.addSubview(titleTextField)
        titleTextField.snp.makeConstraints { make in
            make.leading.equalTo(titleTitleLabel.snp.trailing).offset(16)
            make.top.bottom.equalToSuperview()
            make.trailing.equalToSuperview().inset(16)
        }
    }
    
    @objc private func finishButtonTapped() {
        onFinishButtonTapped?(titleTextField.text)
    }
}


class CollectionItemCell: UIView, SwipeableCellContent {
    
    var onStatusButtonTapped: (() -> Void)?

    private let titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hexString: "#1C1F1E")
        label.font = .systemFont(ofSize: 17, weight: .medium)
        return label
    }()
    
    private let countLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hexString: "#CCCCCC")
        label.font = .systemFont(ofSize: 12, weight: .bold)
        return label
    }()
    
    private lazy var statusButton: UIButton = {
        let button = UIButton(type: .system)
        button.backgroundColor = UIColor(hexString: "#15CC9D")
        button.layer.cornerRadius = 14
        button.setTitle("开始背词", for: .normal)
        button.setTitleColor(UIColor(hexString: "#FFFFFF"), for: .normal)
        button.titleLabel?.font = .systemFont(ofSize: 13, weight: .medium)
        button.addTarget(self, action: #selector(statusButtonTapped), for: .touchUpInside)
        button.layer.shadowColor = UIColor(hexString: "#000000")?.withAlphaComponent(0.1).cgColor
        button.layer.shadowOpacity = 1
        button.layer.shadowOffset = CGSize(width: 0, height: 0)
        button.layer.shadowRadius = 4
        return button
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupCell()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupCell() {
        backgroundColor = UIColor(hexString: "FFFFFF")

        addSubview(titleLabel)
        addSubview(countLabel)
        addSubview(statusButton)
        
        titleLabel.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(12)
            make.centerY.equalToSuperview()
        }
        
        countLabel.snp.makeConstraints { make in
            make.leading.equalTo(titleLabel.snp.trailing).offset(6)
            make.centerY.equalToSuperview()
        }
        
        statusButton.snp.makeConstraints { make in
            make.trailing.equalToSuperview().inset(12)
            make.centerY.equalToSuperview()
            make.height.equalTo(28)
            make.width.equalTo(76)
        }
    }
    
    @objc private func statusButtonTapped() {
        onStatusButtonTapped?()
    }
    
    func configure<Model>(with model: Model) {
        if let item = model as? CollectionItemModel {
            titleLabel.text = item.title
            countLabel.text = "\(item.count)"
            statusButton.setTitle(item.status == 0 ? "开始背词" : "继续背词", for: .normal)
        }
        
    }

}

struct CollectionItemModel: Hashable {
    let title: String
    let count: Int
    let status: Int
}
